package com.androwit.engine.mapping.converter.str;

import com.androwit.engine.mapping.Converter;

public class EnumConverter<T extends Enum<T>> implements Converter<T, String> {
	protected T[] enums;
	protected EnumLabeller<T> labeller;

	public EnumConverter(T[] enums) {
		this(enums, null);
	}

	public EnumConverter(T[] enums, EnumLabeller<T> labeller) {
		if (enums.length == 0)
			throw new IllegalArgumentException("enums must have at least one element");
		this.enums = enums;
		this.labeller = labeller;
	}

	@Override
	@SuppressWarnings( { "unchecked", "static-access" })
	public T fromConverted(String value) throws Exception {
		if (value == null)
			return null;

		if (labeller == null)
			return (T) enums[0].valueOf(enums[0].getClass(), value);

		for (T current : enums) {
			String label = labeller.getLabel(current);
			if (label == value || label.equals(value))
				return current;
		}
		throw new IllegalArgumentException(value);
	}

	@Override
	public String convert(T value) throws Exception {
		if (labeller == null)
			return value == null ? null : value.name();
		return labeller.getLabel(value);
	}

}
